package com.servlet.admin;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.entity.Product;
import com.entity.ProductCategory;
import com.service.layui.impl.LayuiServiceImpl;
import com.service.product.impl.ProductCategoryServiceImpl;
import com.service.product.impl.ProductServiceImpl;
import com.servlet.BaseServlet;
import com.utils.EmptyUtils;
import com.utils.Pager;
import com.utils.ReturnResult;
import com.utils.StringUtils;

@WebServlet("/ProductCategoryService")
public class ProductCategoryService extends BaseServlet {
	private static final long serialVersionUID = 1L;
	private static final String TMP_DIR_PATH = "D:\\tmp";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "/files";
	private File destinationDir;
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.exists()) {//如果目录不存在，则新建目录
			tmpDir.mkdirs();
		}
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		destinationDir.mkdirs();
		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}
	}
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	

	/**
	 * 分类管理
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String category(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取当前页数！
		String currentPageStr = request.getParameter("currentPage");
		// 获取页大小！
		String pageSize = request.getParameter("pageSize");
		int rowPerPage = EmptyUtils.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize);
		int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
		// 获取总页数！
		int count = new ProductServiceImpl().finCategoryCount();
		Pager pager = new Pager(count, rowPerPage, currentPage);
		if (pager.getPageCount() < pager.getCurrentPage()) {
			pager.setCurrentPage(currentPage - 1);

		}
		List<ProductCategory> listCategoryP = new ProductServiceImpl()
				.getProductCategoryAll(null);
		pager.setUrl("/ProductCategoryService?action=category");
		request.setAttribute("pager", pager);
		request.setAttribute("menu", 4);
		// 调用三层！
		List<ProductCategory> listCategory = new ProductServiceImpl()
				.getProductCategoryAll(pager);
		request.setAttribute("listCategoryP", listCategoryP);
		request.setAttribute("listCategory", listCategory);
		return "backend/user/Member_Money";
	}
	
	/**
	 * 删除商品信息！
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	public ReturnResult delCategory(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		String type=request.getParameter("type");
		
		// 执行删除的时候先进去判断！
		int find = new ProductServiceImpl().findParentId(Integer.parseInt(id));
		int count = new ProductServiceImpl().getdParentId(type, Integer.parseInt(id));
		int del = -1;
		// 实例化向页面输出对象！
		ReturnResult result = new ReturnResult();
		// 判断外键是否有数据！
		if(find == 0&&count==0) {
			// 调用三层！
			del = new ProductServiceImpl().deleteEasybuyProductCategoryById(Integer.parseInt(id));
			// 判断是否删除成功！
			if (del > 0) {
				result.returnYes("删除成功！");
			}else {
				// 删除失败！！
				result.returnNo("该分类下有商品，无法删除！");
			}
		}else {
			// 删除失败！！
			result.returnNo("该分类下有商品，无法删除！");
		}
		return result;
	}
	
	/**
	 * 根据Id查询对应的商品信息传递到修改页面！
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String getProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取ID！
		String id = request.getParameter("id");
		String currentPage = request.getParameter("currentPage");
		// 调用三层！
		Product easybuyProduct = new ProductServiceImpl().finBtnProduct(Integer.parseInt(id));
		// 调用三层！
		List<ProductCategory> listOne = new ProductCategoryServiceImpl().finProductCategoryListOne();
  		List<ProductCategory> listTwo = new ProductCategoryServiceImpl().finProductCategoryListTwo();
 		List<ProductCategory> listThree = new ProductCategoryServiceImpl().finProductCategoryListThree();
		// 放到内置对象！
		request.setAttribute("listOne", listOne);
 		request.setAttribute("listTwo", listTwo);
 		request.setAttribute("listThree", listThree);
 		request.setAttribute("currentPage", currentPage);
		// 存放在内置对象中！
		request.setAttribute("easybuyProduct", easybuyProduct);
		return "/backend/product/toAddProduct";
	}
	
	/**
	 * 根据id删除商品！
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ReturnResult deleteById(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ReturnResult result = new ReturnResult();
		// 获取商品ID！
		String id = request.getParameter("id");
		// 调用三层！
		int del = new ProductCategoryServiceImpl().finDelProductById(Integer.parseInt(id));
		// 判断是否删除成功！
		if (del > 0) {
			result.returnYes("操作成功！");
		} else {
			result.returnNo("该商品可能在其他商品中有关联数据~ 不能删除哦！");
		}
		return result;
	}
	
	/**
	 * 商品上架！
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public String toAddUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<ProductCategory> listOne = new ProductCategoryServiceImpl().finProductCategoryListOne();
		request.setAttribute("listOne", listOne);
		Product easybuyProduct = new Product();
		// 放一个空的商品信息对象！
		request.setAttribute("easybuyProduct", easybuyProduct);
		request.setAttribute("menu", 6);
		return "/backend/product/toAddProduct";
	}
	
	/**
	 * 添加分类根据一级分类获取二级分类信息！
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String getProductCategoryTwo(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取一级分类的商品ID！
		String parentId = request.getParameter("parentId");
		// 访问三层！
		List<ProductCategory> productCategoryList2 = new ProductCategoryServiceImpl().getProductCategoryListByparentId(2, Integer.parseInt(parentId));
		// 放置对象！
		request.setAttribute("listTwo", productCategoryList2);
		return "backend/product/toAddProduct";
	}

	/**
	 * 添加分类根据二级分类获取三级分类信息！
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String getProductCategoryThree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取二级分类的商品ID！
		String parentId = request.getParameter("parentId");
		// 访问三层！
		List<ProductCategory> productCategoryList3 = new ProductCategoryServiceImpl().getProductCategoryListByparentId(3, Integer.parseInt(parentId));
		request.setAttribute("listThree", productCategoryList3);
		return "backend/product/toAddProduct";
	}
	
	/**
	 * 修改商品信息！
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String updateAndDel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Pager pager = null;
		// 获取当前页数
		String currentPageStr = request.getParameter("currentPage");
		// 获取页大小
		String pageSize = request.getParameter("pageSize");
		//页面条数
		int rowPerPage = EmptyUtils.isEmpty(pageSize) ? 5 : Integer.parseInt(pageSize);
		//当前页
		int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
		// 获取总记录数！
		int total = new ProductServiceImpl().finProCount();
		// 分页操作！
		int pageCount=(total % rowPerPage == 0)?(total / rowPerPage):(total / rowPerPage)+1;
		String sid=request.getParameter("id");
		int id=EmptyUtils.isEmpty(sid)?0:Integer.parseInt(sid);
		if(id==0) {
			pager = new Pager(total, rowPerPage, pageCount);
		}else {
			pager= new Pager(total, rowPerPage, currentPage);
		}
		if(pager.getPageCount()<pager.getCurrentPage()) {
			pager.setCurrentPage(currentPage);
			
		}
		pager.setUrl("/ProductServlet?action=index");
		// 访问三层！
		List<Product> productList = new LayuiServiceImpl().finProduct(pager);
		// 放置对象！
		request.setAttribute("productList", productList);
		request.setAttribute("pager", pager);
		request.setAttribute("menu", 5);
		return "/backend/product/productList";
	}
	
	/**
	 * 上传
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
		public ReturnResult getImgs(HttpServletRequest request, HttpServletResponse response) throws Exception {
			// ************
			ReturnResult result = new ReturnResult();
			// ************
			Product product = new Product();
			String fieldName = ""; // 表单字段元素的name属性值
			// 请求信息中的内容是否是multipart类型
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);		
			if (isMultipart) {// 是多文件类型
				// 创建对象
				DiskFileItemFactory factory = new DiskFileItemFactory();
				// 设置缓冲区大小4kb
				factory.setSizeThreshold(4096);			
				factory.setRepository(tmpDir);
				ServletFileUpload upload = new ServletFileUpload(factory);
				// 设置单个文件的最大限制
				upload.setFileSizeMax(1024 * 30*1024);
			
				// 解析表单中所有信息
				try {
					// 获得request中的FileItem集合
					@SuppressWarnings("unchecked")
					List<FileItem> items = upload.parseRequest(request);
					Iterator<FileItem> iter = items.iterator();
					while (iter.hasNext()) {
						FileItem item = iter.next();
						if (!item.isFormField()) { // 文件表单字段
							 String fileName  = item.getName().substring(item.getName().lastIndexOf("."));
							 File file = new File(destinationDir, fileName);
							 fileName = StringUtils.randomUUID()
							 + item.getName().substring(
							 item.getName().lastIndexOf("."));
							 System.out.println("uuid"+StringUtils.randomUUID());
							 System.out.println("item.getName()"+item.getName());
							 System.out.println("item.getName()"+item.getName());
							 System.out.println("item.getName().lastIndexOf"+item.getName().lastIndexOf("."));
							 System.out.println(item.getName().substring( item.getName().lastIndexOf(".")));
							 file = new File(destinationDir, fileName);//图片名与商品ID一致
							// 通过Arrays类的asList()方法创建固定长度的集合
							List<String> filType = Arrays.asList("gif", "bmp", "jpg");
							String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
							if (!filType.contains(ext)) // 判断文件类型是否在允许范围内
								return result.returnNo("上传失败，文件类型只能是gif、bmp、jpg");
							else {
								if (fileName != null && !fileName.equals("")) {		
									// ************
									product.setFileName(file.getName());
									// ************
									item.write(file);//保存商品图片
								}
							}
						} else {// 普通表单信息
								// ************
							fieldName = item.getFieldName();
							if (fieldName != null && !fieldName.equals("")) {
								if (fieldName.equals("categoryLevel1Id")) {
									product.setCategoryLevel1(Integer.parseInt(item.getString("UTF-8")));
								} else if (fieldName.equals("categoryLevel2Id")) {
									product.setCategoryLevel2(Integer.parseInt(item.getString("UTF-8")));
								} else if (fieldName.equals("categoryLevel3Id")) {
									product.setCategoryLevel3(Integer.parseInt(item.getString("UTF-8")));
								} else if (fieldName.equals("name")) {
									product.setName(item.getString("UTF-8"));
								} else if (fieldName.equals("price")) {
									product.setPrice(Float.parseFloat(item.getString("UTF-8")));
								} else if (fieldName.equals("stock")) {
									product.setStock(Integer.parseInt(item.getString("UTF-8")));
								} else if (fieldName.equals("description")) {
									product.setDescription(item.getString("UTF-8"));
								} else if (fieldName.equals("id")) {
									product.setId(Integer.parseInt(item.getString("UTF-8")));
								}
								
							}
							// ************
						}
					}
					// 调用三层，添加数据到数据库中
									
				} catch (FileUploadBase.SizeLimitExceededException ex) {
					return result.returnNo("上传失败，文件太大，单个文件的最大限制是：" + upload.getSizeMax() + "bytes!");
				} catch (Exception e) {			
					e.printStackTrace();
				}

			}
			// 访问三层！
			int count = new ProductCategoryServiceImpl().finAddProduct(product);
			// 判断是否上传成功！
			if(count>0) {
				return result.returnYes("操作成功！");	
			}else {
				return result.returnNo("操作失败！请联系管理员。。");
			}
		}

	@Override
	public Class<?> getServletClass() {
		// TODO Auto-generated method stub
		return ProductCategoryService.class;
	}

}
